/**
 * 说明：
 * 创建人：pluto
 * 创建时间：2018/8/23
 */

angular.module('app.imageupload', ['angularFileUpload'])
    .directive('ngImgUpload', ['FileUploader', function (FileUploader) {
        return {
            restrict: 'EA',
            template: '<div>' +
            '<div style="margin-bottom: 10px;">' +
            '</div>' +
            '<ul style="list-style-type: none;padding:0; margin:0;">' +
            '<li ng-repeat="file in files" style="width: 100px;height: 100px;float: left; position: relative;border: 1px solid #ddd;border-radius: 4px;padding: 5px;margin: 0 10px 10px 0;">' +
            '<img ng-src="{{file.datauri}}" style="width: 100%;height: 100%;">' +
            '<button type="button" style="position: absolute; top: -4px; right: 2px;" class="close" ng-click="removeItem($index)">&times;</button>' +
            '</li>' +
            '<li style="float: left;" ng-show="files.length<queueLimit">' +
            '<label class="btn btn-default" style="width:100px;height: 100px;padding: 13px;">' +
            '<input type="file" style="display: none;padding: 0; margin: 0;" nv-file-select="" uploader="uploader" multiple>' +
            '<img src="./common/images/add_icon@3x.png">' +
            '</label>' +
            '</li>' +
            '</ul></div>',
            replace: true,
            scope: {
                filePaths: '=',
                url: '@',
                queueLimit: '@'
            },
            controller: function ($scope) {
                var token = sessionStorage.getItem("token") || '';
                $scope.fileItems = [];
                $scope.files = [];
                $scope.uploadStatus = false; //定义上传后返回的状态
                var uploader = $scope.uploader = new FileUploader({
                    url: $scope.url,
                    queueLimit: $scope.queueLimit,     //文件个数
                    // removeAfterUpload: true   //上传后删除文件
                    headers:{authorization:token}
                });
                $scope.clearItems = function () {    //重新选择文件时，清空队列，达到覆盖文件的效果
                    uploader.clearQueue();
                };
                $scope.getFilePaths = function () {
                    $scope.filePaths.length = 0;
                    uploader.queue.map(function (item) {
                        $scope.filePaths.push(item.filePath);
                    });
                };
                //文件上传进度
                uploader.onProgressItem = function (item, progress) {
                    item.progress = {width: progress + '%'};
                };
                uploader.onErrorItem = function (fileItem, response, status, headers) {
                    if (response.data.status === 100 || response.data.status === '100') {
                        //无权限处理
                        setLocalStorage("login_info", null);
                        setTimeout(function () {
                            window.location.href = "login.html";
                        }, 2000);
                        return;
                    }
                    console.log("上传失败");
                };
                uploader.onSuccessItem = function (fileItem, response, status, headers) {
                    if (response.data.status === 100 || response.data.status === '100') {
                        //无权限处理
                        setLocalStorage("login_info", null);
                        setTimeout(function () {
                            window.location.href = "login.html";
                        }, 2000);
                        return;
                    }
                    // $scope.filePaths.push(response.data.filePath);
                    console.log(response.data);
                    fileItem.filePath = response.data.fileUrl;
                    fileItem.progress = {width: '100%'};
                    $scope.getFilePaths();
                };
                $scope.removeItem = function (index) {
                    $scope.files.splice(index, 1);
                    uploader.removeFromQueue(index);
                    $scope.fileItems = uploader.queue;
                    $scope.getFilePaths();
                };
                $scope.uploadFile = function () {
                    uploader.uploadAll();
                };
                uploader.onAfterAddingAll = function (fileItem) {
                    $scope.fileItems = uploader.queue;
                    for (var i = 0; i< $scope.fileItems.length; i++){
                        var reader = new FileReader();
                        reader.addEventListener("load", function (e) {
                            //文件加载完之后，更新angular绑定
                            $scope.$apply(function(){
                                $scope.files.push({datauri: e.target.result});
                            });
                        }, false);
                        reader.readAsDataURL($scope.fileItems[i]._file);
                    }
                    console.log('aaaa');
                    uploader.uploadAll();
                };
            },
            link: function (scope, element, attrs) {
                console.log(attrs);
                console.log('aaa')
            }
        }
    }])
    .directive('ngImgcanvas', ['$window', function ($window) {
        var helper = {
            support: !!($window.FileReader && $window.CanvasRenderingContext2D),
            isFile: function (item) {
                return angular.isObject(item) && item instanceof $window.File;
            },
            isImage: function (file) {
                var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        };

        return {
            restrict: 'A',
            template: '<canvas/>',
            link: function (scope, element, attributes) {
                if (!helper.support) return;

                var params = scope.$eval(attributes.ngImgcanvas);

                if (!helper.isFile(params.file)) return;
                if (!helper.isImage(params.file)) return;

                var canvas = element.find('canvas');
                var reader = new FileReader();

                reader.onload = onLoadFile;
                reader.readAsDataURL(params.file);

                function onLoadFile(event) {
                    var img = new Image();
                    img.onload = onLoadImage;
                    img.src = event.target.result;
                }

                function onLoadImage() {
                    var width = params.width || this.width / this.height * params.height;
                    var height = params.height || this.height / this.width * params.width;
                    canvas.attr({width: width, height: height});
                    canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
                }
            }
        };
    }]);

